package com.mune.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.mune.common.to.es.SkuEsModel;
import com.mune.common.utils.R;
import com.mune.gulimall.search.config.GuliMallElasticSearchConfig;
import com.mune.gulimall.search.constant.EsConstant;
import com.mune.gulimall.search.feign.ProductFeignService;
import com.mune.gulimall.search.service.MallSearchService;
import com.mune.gulimall.search.vo.AttrResponseVo;
import com.mune.gulimall.search.vo.BrandVo;
import com.mune.gulimall.search.vo.SearchParam;
import com.mune.gulimall.search.vo.SearchResult;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MallSearchServiceImpl implements MallSearchService {
  @Autowired
  RestHighLevelClient client;

  @Autowired
  ProductFeignService productFeignService;

  @Override
  public SearchResult search(SearchParam searchParam) {
    // 格式化检索后的数据
    SearchResult result = null;
    // 准备检索请求
    SearchRequest searchRequest = buildSearchRequest(searchParam);
    try {
      // 执行检索请求拿到数据
      SearchResponse search = client.search(searchRequest, GuliMallElasticSearchConfig.COMMON_OPTIONS);
      // 封装成需要的数据
      result = buildSearchResult(search, searchParam);
    } catch (IOException e) {
      e.printStackTrace();
    }

    return result;
  }

  /**
   * 构建结果数据
   *
   * @param response
   * @return
   */
  private SearchResult buildSearchResult(SearchResponse response, SearchParam searchParam) {
    SearchResult result = new SearchResult();
    // 返回所有查询到的商品
    SearchHits hits = response.getHits();
    List<SkuEsModel> esModels = new ArrayList<>();
    if (hits.getHits() != null && hits.getHits().length > 0) {
      for (SearchHit hit : hits.getHits()) {
        String sourceAsString = hit.getSourceAsString();
        SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
          HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
          String string = skuTitle.getFragments()[0].string();
          esModel.setSkuTitle(string);
        }
        esModels.add(esModel);
      }
    }
    result.setProducts(esModels);
    // 聚合查询结果 ===
    Aggregations aggregations = response.getAggregations();
    ParsedNested attr_agg = aggregations.get("attr_agg");
    List<SearchResult.AttrVo> attrsList = new ArrayList<>();
    ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
    for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
      SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
      // 属性的id
      long attrId = bucket.getKeyAsNumber().longValue();
      // 属性的名字
      String attrName = ( (ParsedStringTerms) bucket.getAggregations().get("attr_name_agg") ).getBuckets().get(0).getKeyAsString();
      // 属性的所有可能值
      List<String> attrValues = ( (ParsedStringTerms) bucket.getAggregations().get("attr_value_agg") ).getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
      attrVo.setAttrId(attrId);
      attrVo.setAttrName(attrName);
      attrVo.setAttrValue(attrValues);
      attrsList.add(attrVo);
    }
    result.setAttrs(attrsList);
    List<SearchResult.BrandVo> brandVos = new ArrayList<>();
    ParsedLongTerms brand_agg = aggregations.get("brand_agg");
    for (Terms.Bucket bucket : brand_agg.getBuckets()) {
      SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
      brandVo.setBrandId(bucket.getKeyAsNumber().longValue());
      String brandImg = ( (ParsedStringTerms) bucket.getAggregations().get("brand_img_agg") ).getBuckets().get(0).getKeyAsString();
      String brandName = ( (ParsedStringTerms) bucket.getAggregations().get("brand_name_agg") ).getBuckets().get(0).getKeyAsString();
      brandVo.setBrandImg(brandImg);
      brandVo.setBrandName(brandName);
      brandVos.add(brandVo);
    }
    result.setBrands(brandVos);
    ParsedLongTerms catalog_agg = aggregations.get("catalogId_agg");
    List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
    List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
    for (Terms.Bucket bucket : buckets) {
      SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
      catalogVo.setCatalogId(bucket.getKeyAsNumber().longValue());
      ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
      String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
      catalogVo.setCatalogName(catalogName);
      catalogVos.add(catalogVo);
    }
    result.setCatalogs(catalogVos);
    // 分页属性
    result.setPageNum(searchParam.getPageNum());
    Long total = response.getHits().getTotalHits().value;
    result.setTotal(total);
    // 总页数 = 总记录 % 每页个数 == 0?
    int totalPages = (int) ( total % EsConstant.PRODUCT_PAGESIZE == 0 ? total / EsConstant.PRODUCT_PAGESIZE : total / EsConstant.PRODUCT_PAGESIZE + 1 );
    result.setTotalPages(totalPages);
    List<Integer> pageNav = new ArrayList<>();
    for (int i = 1; i <= totalPages; i++) {
      pageNav.add(i);
    }
    result.setPageNav(pageNav);
    // 构建面包屑导航
    if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {
      List<SearchResult.NavVo> collect = searchParam.getAttrs().stream().map(attr -> {
        SearchResult.NavVo navVo = new SearchResult.NavVo();
        String[] s = attr.split("_");
        navVo.setNavValue(s[1]);
        R r = productFeignService.attrInfo(Long.parseLong(s[0]));
        result.getAttrIds().add(Long.parseLong(s[0]));
        if (r.getCode() == 0) {
          AttrResponseVo data = r.getData("attr", new TypeReference<AttrResponseVo>() {
          });
          navVo.setNavName(data.getAttrName());
        } else {
          navVo.setNavName(s[0]);
        }
        String replace = replaceQueryString(searchParam, attr, "attrs");
        navVo.setLink("http://search.gulimall.com/list.html?" + replace);
        return navVo;
      }).collect(Collectors.toList());
      result.setNavs(collect);
    }
    // 品牌分类面包屑
    if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
      List<SearchResult.NavVo> navs = result.getNavs();
      SearchResult.NavVo navVo = new SearchResult.NavVo();
      R r = productFeignService.brandInfos(searchParam.getBrandId());
      if (r.getCode() == 0) {
        List<BrandVo> brand = r.getData("brand", new TypeReference<List<BrandVo>>() {
        });
        StringBuffer brandName = new StringBuffer();
        String replace = "";
        for (BrandVo brandVo : brand) {
          brandName.append(brandVo.getBrandName()).append(";");
          replace = replaceQueryString(searchParam, brandVo.getBrandId() + "", "brandId");
        }
        navVo.setNavValue(brandName.toString());
        navVo.setLink("http://search.gulimall.com/list.html?" + replace);
      }
      navs.add(navVo);
    }
    return result;
  }

  private String replaceQueryString(SearchParam searchParam, String value, String key) {
    String encode = null;
    try {
      encode = URLEncoder.encode(value, "UTF-8");
      encode = encode.replace("+", "%20");
      encode = encode.replace("%28", "(");
      encode = encode.replace("%29", ")");
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return searchParam.get_queryString().replace("&" + key + "=" + encode, "");
  }

  /**
   * 构建检索请求
   * 需求：模糊匹配->过滤(按照属性，分类，品牌，价格区间，库存)->排序，分页，高亮，聚合分析
   *
   * @return
   */
  private SearchRequest buildSearchRequest(SearchParam searchParam) {
    SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
    /**
     * 模糊匹配->过滤(按照属性，分类，品牌，价格区间，库存)
     */
    // bool-Query
    BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
    // must-模糊匹配
    if (!StringUtils.isEmpty(searchParam.getKeyword())) {
      boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle", searchParam.getKeyword()));
    }
    // bool-Filter

    // 分类
    if (searchParam.getCatalog3Id() != null) {
      boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", searchParam.getCatalog3Id()));
    }
    // 品牌
    if (searchParam.getBrandId() != null && searchParam.getBrandId().size() > 0) {
      boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", searchParam.getBrandId()));
    }
    // 属性 1_苹果:华为  格式:  属性id_值1:值2:值3
    if (searchParam.getAttrs() != null && searchParam.getAttrs().size() > 0) {

      for (String attr : searchParam.getAttrs()) {
        BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
        String[] s = attr.split("_");
        // 属性id
        String attrId = s[0];
        String[] attrValues = s[1].split(":");
        nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
        nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
        QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
        boolQueryBuilder.filter();
      }
    }
    // 是否有库存(默认只查询有库存的索引)
    if (searchParam.getHasStock() != null) {
      boolQueryBuilder.filter(QueryBuilders.termsQuery("hasStock", searchParam.getHasStock() == 1));
    }
    // 价格区间 格式: 50_500 大于等于50小于等于500  _500 500以下
    if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
      String[] s = searchParam.getSkuPrice().split("_");
      RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
      if (s.length == 2) {
        rangeQueryBuilder.gte(s[0]).lte(s[1]);
      } else if (s.length == 1) {
        if (StringUtils.startsWith(searchParam.getSkuPrice(), "_")) {
          rangeQueryBuilder.gte(s[0]);
        }
        if (StringUtils.endsWith(searchParam.getSkuPrice(), "_")) {
          rangeQueryBuilder.lte(s[0]);
        }
      }
      boolQueryBuilder.filter(rangeQueryBuilder);
    }

    sourceBuilder.query(boolQueryBuilder);
    /**
     * 排序，分页，高亮
     */

    // 排序
    if (!StringUtils.isEmpty(searchParam.getSort())) {
      String[] s = searchParam.getSort().split("_");
      SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
      sourceBuilder.sort(s[0], sortOrder);
    }

    // 分页
    sourceBuilder.from(( searchParam.getPageNum() - 1 ) * EsConstant.PRODUCT_PAGESIZE);
    sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

    // 高亮
    if (!StringUtils.isEmpty(searchParam.getKeyword())) {
      HighlightBuilder builder = new HighlightBuilder();
      builder.field("skuTitle");
      builder.preTags("<b style='color:red;'>");
      builder.postTags("</b>");
      sourceBuilder.highlighter(builder);
    }
    /**
     * 聚合分析
     */

    // 品牌聚合
    TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
    brand_agg.field("brandId").size(50);
    // 品牌子聚合
    brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
    brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));

    sourceBuilder.aggregation(brand_agg);

    // 分类聚合
    TermsAggregationBuilder catalogId_agg = AggregationBuilders.terms("catalogId_agg");
    catalogId_agg.field("catalogId").size(20);
    // 分类子聚合
    catalogId_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
    sourceBuilder.aggregation(catalogId_agg);

    // 属性子聚合
    NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
    TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
    attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName"));
    attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue"));
    attr_agg.subAggregation(attr_id_agg);
    sourceBuilder.aggregation(attr_agg);

    String s = sourceBuilder.toString();
    System.out.println("构建的DSL" + s);
    SearchRequest request = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    return request;
  }
}
